var util = require('../../utils/util.js');
var config = require('../../config');
var qcloud = require('../../vendor/wafer2-client-sdk/index');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false,
    phone: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    //获取二维码pid
    var scene = decodeURIComponent(options.scene);
    if (scene == 'undefined') {
      app.globalData._shopId = '';
    } else {
      app.globalData._shopId = scene.split("#")[0];
      app.globalData._goodsId = scene.split("#")[1];
    }
    wx.setNavigationBarTitle({
      title: '微信授权登录',
    })

    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {//用户已经授权过
          that.setData({
            phone: true,
            loading: true
          })
          wx.getUserInfo({
            success: function (res) {
              that.qcloudLogin();
            }
          });
        }
      }
    })
  },

  bindGetUserInfo: function (e) {
    if (e.detail.userInfo != undefined) {
      var that = this;
      that.setData({
        phone: true,
        loading: true
      })
      that.qcloudLogin();
    } else {
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!',
        showCancel: false,
        confirmText: '返回授权',
      })
    }
  },

  getPhoneNumber: function (e) {
    var that = this;
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!',
        showCancel: false,
        confirmText: '返回授权',
      })
    } else {
      wx.request({
        url: app.globalData.host + "/user/decryption",
        data: {
          sessionKey: app.globalData.userInfo.sessionKey,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        success: function (res) {
          let data = res.data
          if (data.code == 2000) {
            that.qcloudLogin();
          }else{
            wx.showModal({
              title: '错误',
              content: data.msg,
            })
          }
        }
      })
    }
  },
  // 登录获取用户信息
  qcloudLogin: function () {
    var that = this;
    qcloud.login({
      success(result) {
        if (result) {
          app.globalData.userInfo = result;
          that.qcloudrequest()
        } else {
          // 如果不是首次登录，不会返回用户信息，请求用户信息接口获取
          that.qcloudrequest()
        }
      },
      fail(error) {
        util.showModel('登录失败', error)
      }
    })
  },
  qcloudrequest: function () {
    var that = this;
    qcloud.request({
      url: config.service.requestUrl,
      login: true,
      success(result) {
        if (result.data.code == 2000) {
          app.globalData.userInfo = result.data.data;
          if (result.data.data.phone == null || result.data.data.phone == '') {
            that.setData({
              phone: false,
              loading: true
            })
            return false
          }
          wx.setStorage({
            key: "userInfo",
            data: result.data.data
          })

          // 登陆成功，跳转到小程序首页
          if (app.globalData._shopId == undefined || app.globalData._shopId == "") {
            if (result.data.data.tel == null || result.data.data.tel == ''){
              app.toLogin();
            } else {
              app.toIndexOnline();
            }            
          } else {
            wx.request({
              url: app.globalData.host + "/index/store",
              data: util.json2Form({ shop_id: app.globalData._shopId }),
              header: {
                "Content-Type": "application/x-www-form-urlencoded"
              },
              method: "POST",
              success: function (res) {
                let data = res.data
                if (data.code == 2000) {
                  app.globalData.shopInfo = data.data
                  if (result.data.data.isbinding == 0 || result.data.data.isbinding == undefined) {
                    wx.request({
                      url: app.globalData.host + "/index/customerStore",
                      data: util.json2Form({ shop_id: app.globalData._shopId, session_key: result.data.data.sessionKey }),
                      header: {
                        "Content-Type": "application/x-www-form-urlencoded"
                      },
                      method: "POST",
                      success: function (res) {
                        let data = res.data
                        if (data.code == 2000) {
                          if (app.globalData._goodsId == undefined) {
                            app.toIndex();
                          } else {
                            app.toCart(app.globalData._goodsId);
                          }

                        } else {
                          util.showModel('登录失败', data.msg)
                        }
                      }
                    })
                  } else {
                    if (app.globalData._goodsId == undefined) {
                      app.toIndex();
                    } else {
                      app.toCart(app.globalData._goodsId);
                    }
                  }
                } else {
                  util.showModel('登录失败', data.msg)
                  return;
                }
              }
            })
          }
          // 存储用户信息到本地
          // wx.setStorage({
          //   key: 'userInfo',
          //   data: {
          //     userInfo: res.data.data,
          //   },
          //   success: function (res) {
          //     console.log("存储成功+qcloud.request")
          //   },
          // })
        } else {
          console.log(res.data.msg);
        }
      },
      fail(error) {
        util.showModel('请求失败', error)
      }
    })
  },
})